from flask import Flask,render_template
import matplotlib.pyplot as plt
import numpy as np
import base64
from io import BytesIO
import pandas as pd

import seaborn as sns
from matplotlib import rcParams

app = Flask(__name__)

pd.options.display.max_rows=10
unames = list(str.split('UserID::Gender::Age::Occupation::Zip-code',"::"))
users = pd.read_table(r'.\users.dat', sep='::', header=None, names=unames)

rnames = list(str.split('UserID::MovieID::Rating::Timestamp','::'))
ratings=pd.read_table(r'.\ratings.dat',sep='::',header=None, names=rnames)

mnames = list(str.split('MovieID::Title::Genres',"::"))
movies = pd.read_table(r'.\movies.dat',sep='::',header=None, names=mnames)

data = pd.merge(users,ratings)
data = pd.merge(data,movies)

mean_ratings = data.pivot_table(values='Rating',index='Title',columns='Gender',aggfunc='mean')

ratings_by_title = data.groupby('Title').size()
active_titles = ratings_by_title.index[ratings_by_title>=250]

mean_ratings = mean_ratings.loc[active_titles]
##女性
top_female_ratings = mean_ratings.sort_values(by='F', ascending=False)
top_female_ratings10 = top_female_ratings['F'][:10]
##男性
top_male_ratings = mean_ratings.sort_values(by='M', ascending=False)
top_male_ratings10 = top_male_ratings['M'][:10]


##性别
a = set(top_female_ratings10.index) # 女性
b = set(top_male_ratings10.index)
intersection = mean_ratings.loc[a&b]

##差异
mean_ratings['diff'] = np.abs(mean_ratings['M'] - mean_ratings['F'])
sorted_by_diff = mean_ratings.sort_values(by='diff', ascending=False)[:10].copy()

@app.route('/')
def pic1():

    rcParams['font.size'] = 20
    plt.rcParams['font.sans-serif'] = ['FangSong']  # 用来正常显示中文标签
    sns.barplot(top_female_ratings10.values, top_female_ratings10.index, palette="plasma", alpha=0.25)
    plt.xlabel('评分')
    plt.ylabel('电影名')
    plt.title('最受女性欢迎的十部电影及其评分', {'fontsize': rcParams['axes.titlesize']})
    # figure 保存为二进制文件
    buffer = BytesIO()
    plt.savefig(buffer,dpi=80, bbox_inches='tight')
    plt.close()
    plot_data = buffer.getvalue()
    # 将matplotlib图片转换为HTML
    imb = base64.b64encode(plot_data)  # 对plot_data进行编码
    ims = imb.decode()
    imd = "data:image/png;base64," + ims

    imd2 = pic2()
    imd3 = pic3()
    imd4 = pic4()
    return render_template('index.html', img=imd,img2=imd2,img3=imd3,img4=imd4)


def pic2():

    rcParams['font.size'] = 20
    plt.rcParams['font.sans-serif'] = ['FangSong']  # 用来正常显示中文标签
    sns.barplot(top_male_ratings10.values, top_male_ratings10.index, palette="Blues_r", alpha=1)
    plt.xlabel('评分')
    plt.ylabel('电影名')
    plt.title('最受男性欢迎的十部电影及其评分', {'fontsize': rcParams['axes.titlesize']})

    # figure 保存为二进制文件
    buffer = BytesIO()
    plt.savefig(buffer, dpi=80, bbox_inches='tight')
    plt.close()
    plot_data2 = buffer.getvalue()
    # 将matplotlib图片转换为HTML
    imb2 = base64.b64encode(plot_data2)  # 对plot_data进行编码
    ims2 = imb2.decode()
    imd2 = "data:image/png;base64," + ims2

    return imd2


def pic3():
    intersection.plot.barh()
    plt.legend(prop={'size': 8}, loc='center')
    buffer = BytesIO()
    plt.savefig(buffer, dpi=80, bbox_inches='tight')
    plt.close()
    plot_data3 = buffer.getvalue()
    # 将matplotlib图片转换为HTML
    imb3 = base64.b64encode(plot_data3)  # 对plot_data进行编码
    ims3 = imb3.decode()
    imd3 = "data:image/png;base64," + ims3

    return imd3

def pic4():
    sorted_by_diff.plot.barh()
    plt.legend(prop={'size': 8}, loc='center')
    plt.xlabel('评分')
    plt.ylabel('电影名')
    plt.title('性别差异最大的top10电影', {'fontsize': rcParams['axes.titlesize']})
    buffer = BytesIO()
    plt.savefig(buffer, dpi=80, bbox_inches='tight')
    plt.close()
    plot_data3 = buffer.getvalue()
    # 将matplotlib图片转换为HTML
    imb3 = base64.b64encode(plot_data3)  # 对plot_data进行编码
    ims3 = imb3.decode()
    imd3 = "data:image/png;base64," + ims3

    return imd3

if __name__ == '__main__':
    app.run()
